<?php

namespace app\api\controller;
use app\common\model;

use app\common\controller\Api;

/**
 * 教师
 */
class Teacher extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function school()
    {
        $teacher = model\Teacher::where('user_id', $this->auth->id)->find();
        if (!$teacher) {
            $this->error('教师信息不存在');
        }

        $school = model\School::get($teacher->school_id);
        if (!$school) {
            $this->error('学校信息不存在');
        }

        $teaches = model\Teach::alias('teach')
            ->join('__BP_SUBJECT__ subject', 'subject.id = teach.sub_id')
            ->where('teach.school_id', $school->id)
            ->where('teach.teacher_id', $teacher->id)
            ->field('teach.class_id,subject.id,subject.sub_name,subject.type')
            ->select();

        $class_ids = array_unique(array_column($teaches, 'class_id'));

        $data['id'] = $school->id;
        $data['name'] = $school->name;
        if ($class_ids) {
            $result = model\Classes::with('grade')
                ->withCount('student')
                ->where('school_id', $school->id)
                ->whereIn('id', $class_ids)
                ->select();

            $classes = [];
            foreach ($result as $key => $value) {
                $classes[$value->id] = $value;
            }

            foreach ($teaches as $key => $teach) {
                if (isset($classes[$teach->class_id])) {
                    $cla = $classes[$teach->class_id];
                    $data['classes'][] = array_merge([
                        'id' => $cla->id,
                        'name' => $cla->name,
                        'grade_name' => $cla->grade->name,
                        'student_count' => $cla->student_count,
                    ], [
                        'subject_name' => $teach->sub_name,
                        'subject_type' => $teach->type,
                    ]);
                }
            }

        }

        $this->success('', $data);
    }

}
